package com.tiantian.subject.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.util.StrUtil;
import com.tiantian.common.core.domain.ResponseResult;
import com.tiantian.common.core.domain.page.TableDataInfo;
import com.tiantian.common.core.exception.BusinessException;
import com.tiantian.common.core.validate.AddGroup;
import com.tiantian.common.core.validate.EditGroup;
import com.tiantian.common.idempotent.annotation.RepeatSubmit;
import com.tiantian.common.log.annotation.Log;
import com.tiantian.common.log.enums.BusinessType;
import com.tiantian.common.log.enums.OperatorType;
import com.tiantian.common.satoken.domain.controller.BaseController;
import com.tiantian.subject.domain.entity.Subject;
import com.tiantian.subject.domain.entity.UserSolve;
import com.tiantian.subject.service.SubjectService;
import com.tiantian.subject.service.UserSolveService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @author tiantian
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/reply")
public class UserSolveController extends BaseController {

    private final UserSolveService userSolveService;
    private final SubjectService subjectService;

    /**
     * 分页查询
     *
     * @param UserSolve 实体筛选条件
     * @return 分页数据
     */
    @GetMapping("/list")
    public TableDataInfo selectPage(UserSolve UserSolve) {
        startPage();
        List<UserSolve> UserSolves = userSolveService.selectList(UserSolve);
        return getDataTable(UserSolves);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param replyId 主键
     * @return 单条数据
     */
    @GetMapping("/{replyId}")
    public ResponseResult<UserSolve> selectOneById(@PathVariable String replyId) {
        if (StrUtil.isEmpty(replyId)) {
            return ResponseResult.fail("答题ID不能为空");
        }
        return ResponseResult.ok(userSolveService.selectById(replyId));
    }

    /**
     * 查询我的答案
     *
     * @param topicId 题目ID
     */
    @GetMapping("/myAns/{topicId}")
    @SaCheckLogin
    public ResponseResult<Subject> getMyAns(@PathVariable String topicId) {
        if (StrUtil.isEmpty(topicId)) {
            return ResponseResult.fail("题目ID不能为空");
        }
        Long userId = getUserId();
        if (userSolveService.checkReplyUnique(topicId, userId) == 0) {
            return ResponseResult.fail("操作失败,您未提交任何解题");
        }
        Subject sysTopic = subjectService.getSubjectDetail(topicId);
        // 答题模板设置成 [我的答案]
        String ans = userSolveService.selectAnsByTopicIdAndUserId(topicId, userId);
        sysTopic.setCodeTemplate(ans);
        return ResponseResult.ok(sysTopic);
    }

    /**
     * 修改答案
     *
     * @param userSolve UserSolve
     */
    @PutMapping("/updateAns")
    @Log(businessType = BusinessType.NEWCOMER_UPDATE_ANS, operatorType = OperatorType.NEWCOMER, isSaveResponseData = false)
    @RepeatSubmit(interval = 6, timeUnit = TimeUnit.SECONDS, message = "题目已修改,请勿频繁提交")
    public ResponseResult<String> updateMyAns(@RequestBody @Validated(EditGroup.class) UserSolve userSolve) {
        checkTopicExist(userSolve.getTopicId());
        // 修改答案
        Boolean insert = userSolveService.changAnswer(userSolve);
        return insert ? ResponseResult.ok("修改成功", userSolve.getReplyId()) : ResponseResult.fail("未知异常,提交失败,请联系管理员");
    }


    /**
     * 提交解题
     *
     * @param userSolve 实体类
     * @return 提交编号
     */
    @PostMapping("/ans")
    @RepeatSubmit(interval = 6, timeUnit = TimeUnit.SECONDS, message = "题目已提交,请勿频繁提交解题")
    @Log(businessType = BusinessType.NEWCOMER_SUBMIT_TOPIC, operatorType = OperatorType.NEWCOMER, isSaveResponseData = false)
    public ResponseResult<String> submitSolution(@RequestBody @Validated(AddGroup.class) UserSolve userSolve) {
        checkTopicExist(userSolve.getTopicId());
        Boolean insert = userSolveService.insert(userSolve);
        return insert ? ResponseResult.ok("提交成功", userSolve.getReplyId()) : ResponseResult.fail("未知异常,提交失败,请联系管理员");
    }

    /**
     * 检查题目是否存在
     *
     * @param topicId 题目ID
     */
    private void checkTopicExist(String topicId) {
        if (!subjectService.checkSubjectExist(topicId)) {
            throw new BusinessException("题目编号不存在, 操作失败");
        }
    }

}

